using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class Player : MonoBehaviour
{
    // Start is called before the first frame update

    public float movespeed = 3;
    public GameObject bullletPrefab;
    public GameObject explosionPerfab;
    public GameObject defendEffectPrefab;
    public Sprite[] tankSprite;//up right down left

    private SpriteRenderer sr;
    private Vector3 bulletEulerAngles;
    private float timeVal;
    private float defendTimeVal = 3;
    private bool isDefended = true;

    private void Awake()
    {
        sr = GetComponent<SpriteRenderer>();
    }

    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //Protected status
        if(isDefended)
        {
            defendEffectPrefab.SetActive(true);
            defendTimeVal -= Time.deltaTime;
            if(defendTimeVal <= 0)
            {
                isDefended = false;
                defendEffectPrefab.SetActive(false);
            }
        }
        //Attack CD
        if(timeVal >= 0.4f)
        {
            PlayerAttack();
        }
        else
        {
            timeVal += Time.deltaTime;
        }
    }

    private void FixedUpdate()
    {
        Playermove();
        PlayerAttack();
        
    }

    //The ways of attack of players
    private void PlayerAttack()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Instantiate(bullletPrefab, transform.position, Quaternion.Euler(transform.eulerAngles + bulletEulerAngles));
            timeVal = 0;
        }
            
    }

    //The ways of moving of players
    private void Playermove()
    {
        float v = Input.GetAxisRaw("Vertical");

        transform.Translate(Vector3.up * v * movespeed * Time.fixedDeltaTime, Space.World);

        if (v < 0)
        {
            sr.sprite = tankSprite[2];
            bulletEulerAngles = new Vector3(0, 0, -180);
        }

        else if (v > 0)
        {
            sr.sprite = tankSprite[0];
            bulletEulerAngles = new Vector3(0, 0, 0);
        }

        if (v != 0)
        {
            return;
        }

        float h = Input.GetAxisRaw("Horizontal");
        transform.Translate(Vector3.right * h * movespeed * Time.fixedDeltaTime, Space.World);
        if (h < 0)
        {
            sr.sprite = tankSprite[3];
            bulletEulerAngles = new Vector3(0, 0, 90);
        }

        else if (h > 0)
        {
            sr.sprite = tankSprite[1];
            bulletEulerAngles = new Vector3(0, 0, -90);
        }
    }

    //Die
    private void Playerdie()
    {
        if (isDefended)
        {
            return;
        }

        //Explode
        Instantiate(explosionPerfab, transform.position, transform.rotation);
        //Die
        Destroy(gameObject);
    }
}
